//
//  ApprovalDetailViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/12.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

class PayApprovalDetailViewController: BaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ChangePage {
    
    func change(toPage idx: Int) {
        
        if let vc = page.viewControllers?[0] {
            
            if let currentIndex = ctls.index(of: vc) {
                
                if currentIndex < idx {
                    
                    page.setViewControllers([ctls[idx]], direction: .forward, animated: true, completion: nil)
                    
                } else {
                    page.setViewControllers([ctls[idx]], direction: .reverse, animated: true, completion: nil)
                }
                
            }
        }
    }
    
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx > 0 {
                
                return ctls[idx - 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx < ctls.count - 1 {
                
                return ctls[idx + 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed {
            
            let vc = pageViewController.viewControllers![0]
            
            if let index = ctls.index(of: vc) {
                
                slide.slide(toPosition: index)
                
            }
            
        }
    }
    
    
    var applyid = ""
    
    var applyType = ""
    
    var ctls: Array<UIViewController> = []
    
    let page = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
    
    let slide = SlidePageView.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 55)))
    
    let approvalBtn = UIButton(type: .system)
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        approvalBtn.setTitle("审批意见", for: .normal)
        
        approvalBtn.setTitleColor(UIColor.white, for: .normal)
        
        approvalBtn.setTitleColor(UIColor.hex("999999"), for: .disabled)
        
        approvalBtn.backgroundColor = UIColor.mainColor
        
        approvalBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        
        approvalBtn.addTarget(self, action: #selector(approvalAction(_:)), for: .touchUpInside)
        
        page.delegate = self
        
        page.dataSource = self
        
        for view in page.view.subviews {
            if view is UIScrollView {
                let scroll = view as! UIScrollView
                scroll.bounces = false
            }
        }
        
        slide.delegate = self
        
        slide.backgroundColor = UIColor.white
        
        self.view.addSubview(slide)
        
        page.view.backgroundColor = UIColor.white
        
        self.view.addSubview(page.view)
        
        for view in page.view.subviews {
            
            if let scroll = view as? UIScrollView {
                
                scroll.delegate = slide
                
            }
        }
        
        let payinfo = PurchaseTableViewController()
        
        self.ctls.append(payinfo)
        
        let associateinfo = TitleContentTableViewController()
        
        self.ctls.append(associateinfo)
        
        let record = ApprovalRecordListViewController()
        
        self.ctls.append(record)
        
        page.setViewControllers([self.ctls[0]], direction: .forward, animated: true, completion: nil)
        
        self.view.addSubview(approvalBtn)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshBtn), name: NSNotification.Name("RefreshDetail"), object: nil)
        
        self.load(with: "detail")
    }
    
    @objc func refreshBtn()->Void{
        self.popobjc()
        
    }
    
//    let approval = ApprovalSuggestionViewController()
    
    @objc func approvalAction(_ : UIButton) -> Void {
        
        let approval = ApprovalSuggestionViewController()
        
        approval.applyId = self.applyid
        
        approval.businessType = self.applyType
        
        self.navigationController?.present(vc: approval)
        
    }
    
    override func viewWillLayoutSubviews() {
        
        super.viewWillLayoutSubviews()
        
        slide.width = self.view.width
        
        slide.configTitles(["付款信息","关联信息","审批记录"])
        
        page.view.frame = CGRect(origin: CGPoint(x: 0, y: slide.bottom), size: CGSize(width: self.view.width, height: self.view.height - slide.height - 55))
        
        self.approvalBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(55)
        }
//        let tray = UIView()
//
//        tray.backgroundColor = .white
//
//        self.view.addSubview(tray)
//
//        let height: CGFloat = 75.0
//
//        tray.frame = CGRect.init(origin: CGPoint.init(x: 0, y: self.view.height - height), size: CGSize(width: self.view.width, height: height))
//
//        let stack = UIStackView.init(frame: CGRect(x: 10, y: 10, width: self.view.width - 20, height: height - 20))
//
//        tray.addSubview(stack)
//
//        stack.distribution = .fill
//
//        stack.alignment = .fill
//
//        stack.axis = .horizontal
//
//        stack.spacing = 30
//
//        let button = UIButton.init(type: .system)
//
//        button.layer.masksToBounds = true
//
//        button.layer.cornerRadius = 6
//
//        button.backgroundColor = UIColor.mainColor
//
//        button.setTitle("付款确认", for: .normal)
//
//        button.setTitleColor(UIColor.white, for: .normal)
//
//        button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
//
//        button.addTarget(self, action: #selector(payaction), for: .touchUpInside)
//
//        stack.addArrangedSubview(button)
//
//        let cancel = UIButton.init(type: .system)
//
//        cancel.layer.masksToBounds = true
//
//        cancel.layer.cornerRadius = 6
//
//        cancel.backgroundColor = UIColor.red
//
//        cancel.setTitle("取消", for: .normal)
//
//        cancel.titleLabel?.font = UIFont.systemFont(ofSize: 18)
//
//        cancel.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
//
//        cancel.setTitleColor(UIColor.white, for: .normal)
//
//        stack.addArrangedSubview(cancel)
        
//        button.snp.makeConstraints { (make) in
//            make.left.equalToSuperview().offset(30)
//            make.height.equalToSuperview().offset(-20)
//            make.width.equalToSuperview().dividedBy(2.5)
//            make.bottom.equalToSuperview().offset(10)
//        }
//        cancel.snp.makeConstraints { (make) in
//            make.width.equalTo(button.snp.width)
//            make.right.equalToSuperview().offset(30)
//            make.height.equalToSuperview().offset(-20)
//            make.width.equalToSuperview().dividedBy(2.5)
//            make.bottom.equalToSuperview().offset(10)
//        }
    }
    
    @objc func payaction(){
        let scanner = ScanBinaryCodeViewController()
        self.push(destination: scanner)
    }
    
    @objc func cancelAction(){
        self.pop()
    }
    
    
    override var names: Array<String> {
        get{
            return ["detail","refresh"]
        }
    }
    
    override func success(for name: String) -> NetSuccess{
        
        func suc(json: JSON)->Void{
            
            if json.contents?["success"]?.bool == false {
                self.alert(json.contents?["errorMsg"]?.rawString())
                self.pop()
                return
            }
            
            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
                return
            }
            
            if canoperate == true {
                approvalBtn.isEnabled = true
            } else {
                approvalBtn.isEnabled = false
            }
            
            let data = json.contents?["data"]?.contents
            
            let details = data?["details"]?.contents
            
            var contents: Array<Dictionary<String,String?>> = []
            
            contents.append(["付款申请单号:": details?["paymentoddnumber"]?.rawString()])
            
            contents.append(["付款申请人:":details?["createUserName"]?.rawString()])
            
            let paymentmoney = details?["paymentmoney"]?.int ?? 1
            
            contents.append(["本次申请付款金额(元)": String(paymentmoney / 100).rmbformat])
            
            let signingMoney = details?["signingMoney"]?.int ?? 1
            
            contents.append(["本次申请付款比例(%)": String(format: "%.2f", Double(paymentmoney) * 100.0 / Double(signingMoney)) + "%"])
            
            contents.append(["付款条件":details?["admissionrequirements"]?.rawString()])
            
            contents.append(["项目进度":details?["projectschedule"]?.rawString()])
            
            contents.append(["付款事由":details?["paymentreason"]?.rawString()])
            
            contents.append(["其他说明":details?["reset"]?.rawString()])
            
            var attachs: Array<JSON> = []
            
            guard let attachments = details?["attachFiles"]?.array else {
                return
            }
            for item in attachments {
                attachs.append(item)
            }
            
            let purchase = self.ctls[0] as! PurchaseTableViewController
            
            purchase.source = contents
            
            purchase.documents = attachs
            
            var contents1: Array<Dictionary<String,String?>> = []
            
            contents1.append(["项目编号":details?["serialNumber"]?.rawString()])
            
            contents1.append(["项目名称":details?["itemsname"]?.rawString()])
            
            contents1.append(["采购单号":details?["cserialNumber"]?.rawString()])
            
            contents1.append(["采购任务名称":details?["taskName"]?.rawString()])
            
            contents1.append(["合同名称":details?["contractName"]?.rawString()])
            
            contents1.append(["合同金额(元)":String(signingMoney / 100).rmbformat])
            
            let invoiceCountMoney = details?["invoiceCountMoney"]?.int ?? 1
            
            contents1.append(["已来票总金额(元)":String(invoiceCountMoney / 100).rmbformat])
            
            contents1.append(["已来票金额比例(%)":String(format: "%.2f", Double(invoiceCountMoney) * 100.0 / Double(signingMoney)) + "%"])
            
            let conuntCheckMoney = details?["conuntCheckMoney"]?.int ?? 0
            
            contents1.append(["已付款总金额(元)":String(conuntCheckMoney / 100).rmbformat])
            
            contents1.append(["已付款比例(%)":String(format: "%.2f", Double(conuntCheckMoney) * 100.0 / Double(signingMoney)) + "%"])
            
            let associateVC = self.ctls[1] as! TitleContentTableViewController
            
            associateVC.source = contents1
            
            if let list = data?["approvalList"]?.array {
                
                let approvalList = self.ctls[2] as! ApprovalRecordListViewController
                
                approvalList.source = list
                
                approvalList.tableView.reloadData()
            }
            
//            contents.append(["采购单号:":details?["serialNumber"]?.rawString()])
//
//            if let type = details?["type"]?.rawString() {
//
//                if type == "serviceEngineering" {
//                    contents.append(["采购类型":"工程类"])
//                } else {
//                    contents.append(["采购类型":"人力类"])
//                }
//
//            } else {
//                contents.append(["采购类型":"未知"])
//            }
//
//            contents.append(["任务名称:":details?["serialNumber"]?.rawString()])
//
//            contents.append(["需求日期:":details?["demandTime"]?.rawString()])
//
//            contents.append(["采购依据:":details?["purchaseBasisName"]?.rawString()])
//
//            if let amount = details?["estimatedAmount"]?.rawValue as? Int {
//
//                let rmb = amount / 100
//
//                contents.append(["预算金额(元):":String(rmb)])
//
//                contents.append(["估算金额(元):":String(rmb)])
//
//            } else {
//
//                contents.append(["预算金额(元):":""])
//
//                contents.append(["估算金额(元):":""])
//            }
//
//            if let ifFrame = details?["weatherFrame"]?.rawValue as? Bool {
//                if ifFrame == true {
//                    contents.append(["是否框架:":"是"])
//                } else {
//                    contents.append(["是否框架:":"否"])
//                }
//            } else {
//                contents.append(["是否框架:":"否"])
//            }
//
//            contents.append(["建议采购方式:":details?["procurementMethod"]?.rawString()])
//
//            contents.append(["暂定包数:":details?["provisionalPacketNumber"]?.rawString()])
//
//            contents.append(["付款方式:":details?["paymentMethod"]?.rawString()])
//
//            contents.append(["进项金额(元):":details?["incomingAmount"]?.rawString()])
//
//            contents.append(["质保期(月):":details?["warrantyPeriod"]?.rawString()])
//
//            contents.append(["专用资质条件:":details?["qualificationConditions"]?.rawString()])
//
//            contents.append(["服务期限:":details?["servicePeriod"]?.rawString()])
//
//            purchase.source = contents
//
//            var attachs: Array<JSON> = []
//
//            guard let attachments = details?["attachFiles"]?.array else {
//                return
//            }
//            for item in attachments {
//                attachs.append(item)
//            }
//
//            purchase.documents = attachs
//
//            ctls.append(purchase)
//
//            self.page.setViewControllers([purchase], direction: .forward, animated: false, completion: nil)
//
//            let type = details?["type"]?.rawString()
//
//            if type == "serviceEngineering" {
//                //3ge标签
//
//                slide.configTitles(["采购信息","项目信息","审批记录"])
//
//                let projectInfo = ProjectInfoViewController.init()
//
//                var contents: Array<Dictionary<String,String?>> = []
//
//                contents.append(["关联项目:":details?["projectName"]?.rawString()])
//
//                contents.append(["项目编号:":details?["proSerialNumber"]?.rawString()])
//
//                contents.append(["项目负责人:":details?["projManagerName"]?.rawString()])
//
//                let applicantInfo = details?["applicantInfo"]?.contents
//
//                contents.append(["联系电话:":applicantInfo?["phone"]?.rawString()])
//
//                contents.append(["申请部门:":applicantInfo?["orgName"]?.rawString()])
//
//                contents.append(["项目背景:":applicantInfo?["projectBackground"]?.rawString()])
//
//                projectInfo.source = contents
//
//                ctls.append(projectInfo)
//
//            }
//
//            let approvalList = ApprovalRecordListViewController()
//
//            if let list = data?["approvalList"]?.array {
//
//                approvalList.source = list
//
//                approvalList.tableView.reloadData()
//            }
//
//            ctls.append(approvalList)
        }
//
//        func refresh(json: JSON)->Void{
//            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
//                return
//            }
//
//            if canoperate == true {
//                approvalBtn.isEnabled = true
//            } else {
//                approvalBtn.isEnabled = false
//            }
//        }
        
            return suc
//        return name == "detail" ? suc : refresh
        
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        return ["applyId":self.applyid,"businessType":self.applyType]
    }
    
    override func path(for name: String) -> String{
//        purchasingManage/pc/sys/approvalprocess/getDetailsByBusinessType
//        return "purchasingManage/mobile/sys/approvalprocess/getDetailsByBusinessType"
        return PurchaseDetail
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
}
